package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.OrderVendorDto;
import com.authine.cloudpivot.ext.dto.OrderVendorGoodsDto;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.service.impl.OrderServiceImpl;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.common.json.JsonUtils;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName VendorOrderService
 * @Description: 销售订单自定义服务
 * @Author cjj
 * @Date 2021/4/20
 * @Version V1.0
 **/
@Path("VendorOrderService")
@Slf4j
public class VendorOrderService extends ApplicationBaseService {
    private OrderService orderService = new OrderServiceImpl();
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 确认接单
     *
     * @param dto
     * @return
     */
    @Path("confirmReceipt")
    @POST
    @Operation(summary = "销售订单-待接单-确认接单", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse<Boolean> confirmReceipt(@Parameter OrderVendorDto dto) {
        log.info("------------------------销售订单-待接单-确认接单 confirmReceipt Param：{}------------------------", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "供应商订单ID集合必填");
        }
        boolean flag = orderService.orderTaking(dto.getIds());
        return SingleResponse.of(flag);
    }

    /**
     * 交易中
     *
     * @param dto
     * @return
     */
    @Path("vendorReturnList")
    @POST
    @Operation(summary = "销售订单-交易中-交易中列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> vendorReturnList(@Parameter OrderVendorDto dto) {
        log.info("------------------------销售订单-代发货-交易中列表 tradeList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String vendorTableName = getTableName(ModelConst.T_ORDER_VENDOR);
        String customerTableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
//        select v.*,c.ero_po,c.receiver,c.phone,c.postal,c.address
        listSql.append("select * from " + vendorTableName + " v " +
                "LEFT JOIN " + customerTableName + " c on c.id = v.order_customer_id " +
                "WHERE v.deleted ='0' and c.deleted ='0' and v.order_vendor_status in ('UpcomingDelivery','DoneDelivery')");
        countSql.append("select count(*) from " + vendorTableName + " v " +
                "LEFT JOIN " + customerTableName + " c on c.id = v.order_customer_id " +
                "WHERE v.deleted ='0' and c.deleted ='0' and v.order_vendor_status in ('UpcomingDelivery','DoneDelivery')");
        //拼接参数
        //供应商订单序号
        if (StringUtils.isNotBlank(dto.getId())) {
            List<String> ids = StringUtils.stringToListString(dto.getId(), ";");
            whereSql.append(" and v.id in (:id) ");
            parameter.put("id", ids);
        }
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and v.order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //eroPO
        if (StringUtils.isNotBlank(dto.getErpPo())) {
            whereSql.append(" and c.erp_po like :erp_po ");
            parameter.put("erp_po", "%" + dto.getErpPo() + "%");
        }
        //下单日期
        if (StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
            whereSql.append(" and v.place_order_time between :startTime and :endTime ");
            parameter.put("startTime", dto.getStartTime());
            parameter.put("endTime", dto.getEndTime());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by v.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------销售订单-代发货-交易中列表 tradeList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------销售订单-代发货-交易中列表 tradeList whereSql：{}------------------------parameter：{}", whereSql, listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_VENDOR);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_VENDOR);
        return SingleResponse.of(bOList);
    }

    /**
     * 待发货
     *
     * @param dto
     * @return
     */
    @Path("vendorDeliveryList")
    @POST
    @Operation(summary = "销售订单-待发货-待发货列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> vendorDeliveryList(@Parameter OrderVendorGoodsDto dto) {
        log.info("------------------------销售订单-代发货-交易中列表 tradeList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String vendorGoodsTableName = getTableName(ModelConst.T_ORDER_VENDOR_GOODS);
        String vendorTableName = getTableName(ModelConst.T_ORDER_VENDOR);
        String customerTableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        String quotationGoodsTableName = getTableName(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select case when vg.tags is null then qg.remark_message else null end as tags, vg.*,v.*,c.* from " + vendorGoodsTableName + " vg " +
                "LEFT JOIN " + vendorTableName + " v on v.id = vg.order_vendor_id " +
                "LEFT JOIN " + customerTableName + " c on c.id = vg.order_customer_id " +
                "LEFT JOIN " + quotationGoodsTableName + " qg on vg.goods_id = qg.id " +
                "where vg.deleted ='0' and v.deleted ='0' and c.deleted ='0' and vg.order_vendor_status in ('UpcomingDelivery','DoneDelivery') ");
        countSql.append("select count(*) from " + vendorGoodsTableName + " vg " +
                "LEFT JOIN " + vendorTableName + " v on v.id = vg.order_vendor_id " +
                "LEFT JOIN " + customerTableName + " c on c.id = vg.order_customer_id " +
                "LEFT JOIN " + quotationGoodsTableName + " qg on vg.goods_id = qg.id " +
                "where vg.deleted ='0' and v.deleted ='0' and c.deleted ='0' and vg.order_vendor_status in ('UpcomingDelivery','DoneDelivery') ");
        //拼接参数
        //订单商品序号
        if (StringUtils.isNotBlank(dto.getId())) {
            List<String> ids = StringUtils.stringToListString(dto.getId(), ";");
            whereSql.append(" and vg.id in (:id) ");
            parameter.put("id", ids);
        }
        //供应商订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderVendorId())) {
            List<String> orderVendorIds = StringUtils.stringToListString(dto.getOrderVendorId(), ";");
            whereSql.append(" and vg.order_vendor_id in (:order_vendor_id) ");
            parameter.put("order_vendor_id", orderVendorIds);
        }
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and vg.order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //eroPO
        if (StringUtils.isNotBlank(dto.getErpPo())) {
            whereSql.append(" and c.erp_po like :erp_po ");
            parameter.put("erp_po", "%" + dto.getErpPo() + "%");
        }
        //品牌
        if (StringUtils.isNotBlank(dto.getBrand())) {
            whereSql.append("and vg.brand like :brand ");
            parameter.put("brand", "%" + dto.getBrand() + "%");
        }
        //名称
        if (StringUtils.isNotBlank(dto.getName())) {
            whereSql.append(" and vg.name like :name ");
            parameter.put("name", "%" + dto.getName() + "%");
        }
        //型号
        if (StringUtils.isNotBlank(dto.getModel())) {
            whereSql.append(" and vg.model like :model ");
            parameter.put("model", "%" + dto.getModel() + "%");
        }
        //规格
        if (StringUtils.isNotBlank(dto.getSpec())) {
            whereSql.append(" and vg.spec like :spec ");
            parameter.put("spec", "%" + dto.getSpec() + "%");
        }
        //下单日期
        if (StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
            whereSql.append(" and vg.place_order_time between :startTime and :endTime ");
            parameter.put("startTime", dto.getStartTime());
            parameter.put("endTime", dto.getEndTime());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by vg.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------销售订单-代发货-交易中列表 tradeList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------销售订单-代发货-交易中列表 tradeList whereSql：{}------------------------parameter：{}", whereSql, listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_ORDER_VENDOR_GOODS);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_VENDOR_GOODS);
        return SingleResponse.of(bOList);
    }

    /**
     * 编辑标记
     *
     * @param dto
     * @return
     */
    @Path("editTag")
    @POST
    @Operation(summary = "销售订单-全部-编辑标记/销售订单-待发货-编辑标记", tags = CUSTOM_SERVICE, description = "id、goodsId、tags必填")
    public SingleResponse<Boolean> editTag(@Parameter OrderVendorGoodsDto dto) {
        log.info("------------------------销售订单-全部-编辑标记/销售订单-待发货-编辑标记 editTag Param：{}------------------------", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "供应商订单商品ID必填");
        }
        if (StringUtils.isBlank(dto.getGoodsId())) {
            return SingleResponse.buildFailure("-1", "供应商订单商品goodsId必填");
        }
        if (StringUtils.isBlank(dto.getTags())) {
            return SingleResponse.buildFailure("-1", "标记信息必填");
        }
        Map<String, Object> goodsPurchase = JdbcTemplateUtils.builder(AppConst.COMMODITYMATERIALS, ModelConst.T_GOODS_PURCHASE).selectField("*")
                .eq("id", dto.getGoodsId()).queryForMap();
        if (null == goodsPurchase) {
            return SingleResponse.buildFailure("-1", "组织采购单数据不存在");
        }
        List<Map<String, Object>> quotationGoods = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS).selectField("*")
                .eq("id", goodsPurchase.get("quotation_goods_id")).queryForList();
        if (quotationGoods.size() == 0) {
            return SingleResponse.buildFailure("-1", "该报价商品可能已被删除或当前账号无权修改");
        }
        if (quotationGoods.size() >= 2) {
            return SingleResponse.buildFailure("-1", "发现多个报价商品, 无法修改");
        }
        Integer i = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS)
                .putFieldAndVal("remark_message", dto.getTags()).eq("id", dto.getGoodsId()).update();
        JdbcTemplateUtils.builder(ModelConst.T_ORDER_VENDOR_GOODS)
                .putFieldAndVal("remark_message", dto.getTags()).eq("id", dto.getId()).update();
        return SingleResponse.of(i >= 0 ? true : false);
    }
}
